package binaryOctopus;

import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.border.Border;

class PieceListener extends MouseAdapter
{
	private static SquarePanel clicked;
	static Coordinates clickedCoordinates[]=new Coordinates [2];
	public static Border defaultBorder = null;
	Board gameBoard = null;
	Border clickedBorder = BorderFactory.createLineBorder(Color.RED, 3);
	
	public PieceListener(Board gameBoard)
	{
		clicked = null;
		this.gameBoard = gameBoard;
	}
	
	@Override
	public void mouseClicked(MouseEvent e) //HANDLE EXCEPTIONS
	{
		if(clicked != null)
		{
			clicked.setBorder(defaultBorder);
		}
		clicked = (SquarePanel) e.getSource();
		defaultBorder = clicked.getBorder();
		
		Coordinates lastClickedCoordinate = new Coordinates(clicked.getmyX(), clicked.getmyY());
		
		if (clickedCoordinates[0] == null)
		{
			//Makes sure that the coordinate selected is a current player's piece
			if(gameBoard.isCurPlayersSquare(lastClickedCoordinate))
			{
				clickedCoordinates[0] = lastClickedCoordinate;
				clicked.setBorder(clickedBorder);
			}
		}
		else
		{
			//Makes sure that the coordinate selected is empty, then move piece
			if(!gameBoard.checkSquare(lastClickedCoordinate))
			{
				clickedCoordinates[1] = lastClickedCoordinate;
				gameBoard.move(clickedCoordinates[0], clickedCoordinates[1]);
				clickedCoordinates[0] = null;
				clickedCoordinates[1] = null;
				
				
			} 
			//If player previously misclicked, assign the new beginning coordinate to his current click
			//so that next click will try to move the current piece as expected
			else if(gameBoard.isCurPlayersSquare(lastClickedCoordinate))
			{
				clickedCoordinates[0] = lastClickedCoordinate;
				clicked.setBorder(clickedBorder);
			}
		}
	}
		
	/*public static Coordinates[] clickTwoSquares()
    {
            System.out.println("Try to press piece");
            int numClicks = 0;
            
            if(numClicks != 2)
            {
                    if(numClicks == 0)
                    {
                            //
                    }
                    
                    if(numClicks == 1)
                    {
                            int x = clicked.getmyX();
                            int y = clicked.getmyY();
                            clickedCoordinates[0] = new Coordinates(x, y);
                    }
            }
            
            
            if(numClicks == 2)
            {
                    int x = clicked.getmyX();
                    int y = clicked.getmyY();
                    clickedCoordinates[1] = new Coordinates(x, y);
            }
            
            return clickedCoordinates;
    }*/

}